import { Ollama } from 'ollama'
import { defineStore } from 'pinia'
import { ref } from 'vue'
export interface IChat {
  id: number
  model: string
  ollama?: Ollama
  messages?: IChatMessage[]
}

export interface IChatMessage {
  id: number
  question: string
  answer: string
  think: string
  questionTime: number
  thinkTime: number
  answerTime: number
}

export const useChatStore = defineStore('useChat', () => {
  const chatList = ref<IChat[]>([])
  const addChat = (modelName: string) => {
    chatList.value.push({
      id: chatList.value.length + 1,
      model: modelName,
      ollama: new Ollama({ host: 'http://127.0.0.1:11434' }),
      messages: [],
    })
  }

  const currentChat = ref<IChat>()
  const setCurrentChat = (id: number) => {
    currentChat.value = chatList.value.find((item) => item.id === id) as IChat
  }

  const sendQuestion = async (question: string) => {
    const message: IChatMessage = {
      id: Date.now(),
      question,
      answer: '',
      think: '',
      questionTime: Date.now(),
      answerTime: 0,
      thinkTime: 0,
    }
    currentChat.value?.messages?.push(message)
    try {
      const res = await currentChat.value.ollama.generate({
        prompt: question,
        model: currentChat.value?.model,
        stream: true,
      })
      for await (const data of res) {
        console.log('🚀 ~ forawait ~ data:', data)
      }
    } catch (error) {
      console.log('🚀 ~ sendQuestion ~ error:', error)
    }
  }

  return {
    chatList,
    addChat,
    currentChat,
    setCurrentChat,
    sendQuestion,
  }
})
